package com.beidouapp.mvc;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.cdhn.util.StringUtil;

import com.beidouapp.cache.impl.RedisDefaultAppCacheHelper;
import com.beidouapp.common.contant.SecurityContant;
import com.beidouapp.exception.BusinessException;
import com.beidouapp.security.model.ReturnDataInfo;
import com.boss.common.HttpUtils;

@Controller
@RequestMapping(value = "/interface")
public class InterfaceController {
	private Logger logger = LoggerFactory.getLogger(MemberController.class);
	static String url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=";
	static String ip = "125.169.30.125";
	@Autowired
	private RedisDefaultAppCacheHelper redisCache;

	@RequestMapping(value = "/lookUpIp/{ip}", method = RequestMethod.GET)
	public @ResponseBody ReturnDataInfo<String> lookUpIp(@PathVariable String ip)
			throws IOException {
		String ipReg = "([1-9]|[1-9]//d|1//d{2}|2[0-4]//d|25[0-5])(//.(//d|[1-9]//d|1//d{2}|2[0-4]//d|25[0-5])){3}";
		if (StringUtil.isBlank(ip)) {
			throw new BusinessException("IP不能為空！");
		}

		Pattern pattern = Pattern.compile(ipReg);
		Matcher matcher = pattern.matcher(ip);

		String info = HttpUtils.get(url + ip, new HashMap<String, Object>());
		if (StringUtil.isBlank(info) || info.indexOf("{") == -1) {
			info = "{\"ret\":-1}";
		}
		JSONObject json = JSONObject.fromObject(info);
		return ReturnDataInfo.createSuccessfulSingleExecuteResult(info);

	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/province", method = { RequestMethod.POST,
			RequestMethod.GET })
	public @ResponseBody ReturnDataInfo<String> province(HttpSession session,
			HttpServletRequest request) {
		try {
			List<String> datas = (List<String>) redisCache.getCacheValue(
					SecurityContant.NAMESPACE, request.getParameter("code"));
			if (CollectionUtils.isEmpty(datas)) {
				datas = Collections.emptyList();
			}
			return ReturnDataInfo.createSuccessfulExecuteResults(datas);
		} catch (Exception ex) {
			return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
		}
	}

	public static void main(String[] args) throws IOException {
		String info = HttpUtils.get(url + ip, new HashMap<String, Object>());
		JSONObject json = JSONObject.fromObject(info);
		System.out.println(json);
	}

}
